import gradio as gr
import pickle
import numpy as np

# 加载已保存的最佳模型
with open('best_ensemble_model.pkl', 'rb') as f:
    model = pickle.load(f)

def predict(img):
    # 灰度化并缩放到32x32
    import cv2
    img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
    img = cv2.resize(img, (32, 32))
    # 展平并归一化
    x = img.reshape(1, -1).astype(np.float32)
    x = x / (np.linalg.norm(x, axis=1, keepdims=True) + 1e-12)
    # 预测
    pred = model.predict(x)[0]
    label = '狗' if pred == 1 else '猫'
    return label

iface = gr.Interface(
    fn=predict,
    inputs=gr.Image(type="numpy"),
    outputs=gr.Textbox(label="预测结果"),
    title="猫狗识别集成学习Web应用",
    description="上传一张猫或狗的图片，模型将自动识别。"
)

if __name__ == "__main__":
    iface.launch()
